/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.utilitarios;

import br.com.foxinline.modelo.Anexo;
import br.com.foxinline.servico.AnexoServico;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class viewImage implements Serializable {

    @EJB
    AnexoServico anexoServico;
    private String url;

    @PostConstruct
    public void init() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        url = params.get("annex");
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void rotateImageDireta() {
        rotateImage(90);
    }

    public void rotateImageEsquerda() {
        rotateImage(-90);
    }

    public void rotateImage(int ang) {
        Anexo a = anexoServico.pesquisar(Long.parseLong(url));

        InputStream bais = new ByteArrayInputStream(a.getArquivo());

        BufferedImage original;
        try {
            original = ImageIO.read(bais);

            BufferedImage dest = new BufferedImage(original.getHeight(), original.getWidth(), original.getType());
            Graphics2D surface = dest.createGraphics();
            AffineTransform rotation = new AffineTransform();
            rotation.setToTranslation((dest.getWidth() - original.getWidth()) / 2.0, (dest.getHeight() - original.getHeight()) / 2.0);
            rotation.rotate(Math.toRadians(ang), original.getWidth() / 2.0, original.getHeight() / 2.0);
            surface.transform(rotation);
            surface.drawImage(original, 0, 0, null);
            surface.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(dest, "jpg", baos);

            a.setArquivo(baos.toByteArray());

            anexoServico.atualizar(a);

            FacesContext.getCurrentInstance().getExternalContext().redirect("viewImage.xhtml?annex=" + a.getId());

        } catch (IOException ex) {
            Logger.getLogger(viewImage.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
